<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<style>
		body,html{
			margin: 0px;
			padding: 0px;
			overflow: hidden;
		}
	</style>
	<body>
		<canvas id="testBall" style="background: #000000;"></canvas>
	</body>
</html>
<script src="js/utils.js"></script>
<script src="Z.js"></script>
<script>
	window.onload = function(){
		var canvas = document.getElementById('testBall');
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;
		var ctx = canvas.getContext('2d');
		var balls = [];
		var ballNums = 250;
		var centerX = canvas.width/2;
		var centerY = canvas.height/2;
		var fl = 250;
		var angleX = 0;
		var angleY = 0;
		mouse = utils.captureMouse(canvas);
		
		for (var i = 0; i < ballNums; i++) {
			var ball = new Ball();
			ball.xpos = Math.random() * 500 - 250;
			ball.ypos = Math.random() * 500 - 250;
			ball.zpos = Math.random() * 500 - 250;
			balls.push(ball);
		}
		
		
		
		
		
		function rotateX(ball, angel){
			var cos = Math.cos(angel);
			var sin = Math.sin(angel);
			var newY = ball.ypos * cos - ball.zpos * sin;
			var newZ = ball.zpos * cos + ball.ypos * sin;
			ball.ypos = newY;
			ball.zpos = newZ;
		}
		
		function rotateY(ball, angel){
			var cos = Math.cos(angel);
			var sin = Math.sin(angel);
			
			newX = ball.xpos * cos - ball.zpos * sin;
			newZ = ball.zpos * cos + ball.xpos * sin;
			
			ball.xpos = newX;
			ball.zpos = newZ;
		}
		
		function setPerpective(ball){
			
			if (ball.zpos > -fl) {
				var scale = fl / (fl + ball.zpos);
				ball.scaleX = ball.scaleY = scale;
				ball.x = centerX + (ball.xpos * scale);
				ball.y = centerY + (ball.ypos * scale);
				
				ball.visible = true;
			}else{
				
				ball.visible = false;
			}
		}
		
		function move(ball){
			rotateX(ball, angleX);
			rotateY(ball, angleY);
			setPerpective(ball);
		}
		
		function draw(ball){
			if (ball.visible) {
				ball.draw(ctx);
			}
		}
		
		function zSort(a, b){
            return (b.zpos - a.zpos);
        }
		
		(function enterFrame(){
			window.requestAnimationFrame (enterFrame, canvas);
			ctx.clearRect(0, 0, canvas.width, canvas.height);
			
			angleX = (mouse.y - centerY) * 0.0001;
			angleY = (mouse.x - centerX) * 0.0001;
			
			balls.forEach(draw);
			balls.forEach(move);
			balls.forEach(zSort)
		}())
		
		
	}
</script>